﻿using System;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.StsAdmin;
using Microsoft.SharePoint.Utilities;
using MSPE.Public.FOSS.AutoStatusPlus.Common;
using MSPE.Public.FOSS.AutoStatusPlus.StsAdm.OperationHelpers;
using MSPE.Public.FOSS.AutoStatusPlus.StsAdm.SPValidators;

namespace MSPE.Public.FOSS.AutoStatusPlus.StsAdm.Commands
{
    public class AspEnumConfig : SPOperation
    {
        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="AspEnumConfig"/> class.
        /// </summary>
        public AspEnumConfig()
        {
            SPParamCollection _parameters = new SPParamCollection
                                               {
                                                   new SPParam(GlobalConstants.UrlParamName, GlobalConstants.UrlParamName, true, null,
                                                               new SPUrlValidator(),
                                                               "Please specify the PWA site URL."),
                                                   new SPParam(GlobalConstants.VerboseParamName, GlobalConstants.VerboseParamName)
                                               };

            StringBuilder _sb = new StringBuilder();
            _sb.AppendLine("-url <URL of PWA Site>");
            _sb.AppendLine("\t[-verbose]");
            _sb.AppendLine();
            _sb.AppendLine();
            _sb.AppendLine("\tThis command enumerates the current AutoStatusPlus settings for");
            _sb.AppendLine("\ta particular PWA site (i.e. Project Server 2007 instance).");
            _sb.AppendLine();
            _sb.AppendLine("\tSpecify the verbose switch to show all settings, regardless");
            _sb.AppendLine("\tof relevancy. For example, without the verbose switch, no");
            _sb.AppendLine("\tlog file related settings will be shown if update logging is off.");

            Init(_parameters, _sb.ToString());
        }
        #endregion // Constructors

        #region Methods
        #region Overrides
        public override int Execute(string command, StringDictionary keyValues, out string output)
        {
            throw new NotImplementedException();
        } // Exebcute()

        /// <summary>
        /// Gets the help message.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <returns></returns>
        public override string GetHelpMessage(string command)
        {
            return HelpMessage;
        } // GetHelpMessage()

        /// <summary>
        /// Runs the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="keyValues">The key values.</param>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        public override int Run(string command, StringDictionary keyValues, out string output)
        {
            SPSite _site = null;
            SPWeb _pwaWeb = null;
            StringBuilder _outputBuilder = null;

            try
            {
                #region Read configuration settings from command line
                output = string.Empty;

                InitParameters(keyValues);

                // Read params into local fields
                string _url = Params[GlobalConstants.UrlParamName].Value.TrimEnd('/');
                bool _verbose = Params[GlobalConstants.VerboseParamName].UserTypedIn;
                #endregion // Read configuration settings from command line
               
                // Get the PWA site
                _site = new SPSite(_url);

                if (_site.Url != _url)
                    throw new Exception("You may only configure Project Web Access Sites.");

                _pwaWeb = _site.RootWeb;

                if (_pwaWeb == null)
                    throw new Exception("Could not load the Site at the specified URL.");

                if (_pwaWeb.WebTemplateId != GlobalConstants.PwaSiteTemplateId)
                    throw new Exception("You may only configure Project Web Access Sites.");

                // Load web's property bag
                SPPropertyBag _pwaWebProperties = _pwaWeb.Properties;

                if (_pwaWebProperties == null)
                    throw new Exception("Unable to retrieve properties for Site.");

                Settings _currentSettings = Settings.LoadSettings(_pwaWeb);

                if (Utility.AllKeysExist(_pwaWeb))
                {
                    _outputBuilder = new StringBuilder();
                    _outputBuilder.AppendFormat("\tAutoStatusPlus Settings for {0}\n", _url);
                    _outputBuilder.AppendLine("\t".PadRight(40,'-'));
                    _outputBuilder.AppendFormat("\tWebIsConfigured: {0}\n", _currentSettings.WebIsConfigured);
                    _outputBuilder.AppendFormat("\tSSP Name: {0}\n", _currentSettings.SspName);
                    _outputBuilder.AppendFormat("\tDatabase Server: {0}\n", _currentSettings.DbServer);
                    _outputBuilder.AppendFormat("\tDatabase Name: {0}\n", _currentSettings.DbName);
                    _outputBuilder.AppendFormat("\tUse Integrated Auth: {0}\n", _currentSettings.DbUseIntegratedAuth);
                    
                    if (!_currentSettings.DbUseIntegratedAuth || _verbose)
                    {
                        _outputBuilder.AppendFormat("\tDatabase User: {0}\n", _currentSettings.DbUser);
                        _outputBuilder.AppendFormat("\tDatabase Password: {0}\n", _currentSettings.DbPassword);
                    }

                    if (_currentSettings.SspHostname != GlobalConstants.SspHostnameInitialValue || _verbose)
                        _outputBuilder.AppendFormat("\tSSP Hostname: {0}\n", _currentSettings.SspHostname);

                    _outputBuilder.AppendFormat("\tLog Updates: {0}\n", _currentSettings.LogUpdates);
                    
                    if (_currentSettings.LogUpdates || _verbose)
                    {
                        _outputBuilder.AppendFormat("\tLog Updates: {0}\n", _currentSettings.LogUpdates);
                        _outputBuilder.AppendFormat("\tLog File Path: {0}\n", _currentSettings.LogFilePath);
                        _outputBuilder.AppendFormat("\tLog File Prefix: {0}\n", _currentSettings.LogFilePrefix);
                        _outputBuilder.AppendFormat("\tNew Log File Every Hour: {0}\n", _currentSettings.NewLogFileEveryHour);
                    }

                    _outputBuilder.AppendFormat("\tLog Timesheet Events: {0}\n", _currentSettings.LogTimesheetEvents);
                    _outputBuilder.AppendFormat("\tProcess Blank Lines: {0}\n", _currentSettings.ProcessBlankLines);
                    _outputBuilder.AppendFormat("\tEvent: {0}\n", Enum.GetName(typeof(TimesheetEventEnum), _currentSettings.Event));
                    _outputBuilder.AppendFormat("\tPolling Interval: {0}\n", _currentSettings.PollingInterval);
                    _outputBuilder.AppendFormat("\tSubmit Updates: {0}\n", _currentSettings.SubmitUpdates);

                    output = _outputBuilder.ToString();
                } // End if

                // Use the ErrorCodes enum to return error codes: 
                // ErrorCodes.SyntaxError
                // ErrorCodes.GeneralError

                // Return 0 for success.
                return 0;
            } // End try

            catch (Exception ex)
            {
                throw new Exception("Error encountered while configuring site:\n\n" + ex.ToString());
            } // End catch

            finally
            {
                if (_pwaWeb != null) _pwaWeb.Dispose();
                if (_site != null) _site.Dispose();
            } // End finally
        } // Run()
        #endregion // Overrides
        #endregion // Methods
    }
}
